<?php


class Diet_check extends CI_Model{
		
	//Gera o diet check para a pessoa por dia
	public function create_diet_check($id_p){
		$data_atual = date("Y-m-d");
		$query = $this->db->get_where('diet', array('id_patient' => $id_p,'active' => 1));
		$id_diet = $query->row()->id;
		
		$query = $this->db->get_where('diet_check', array('date' => $data_atual,'id_diet' => $id_diet));
		
		if ($query->num_rows == 0) {//cria um novo
			
			$query = $this->db->get_where('food_element', array('id_diet' => $id_diet, 'out_diet' => false));
			$food_el = $query->result_array();
			foreach($food_el as $food){
				$data = array(
					'id_food_element' => $food['id'] ,
					'date' => $data_atual,
					'id_diet' => $id_diet
				);
				$this->db->insert('diet_check', $data); 
			}
			return $this->create_diet_check($id_p);
		}else{
			return $query->result_array();
		}
	}
	
	//Retorna o diet check do dia já formatado
	public function view_diet_check($id_p){
		$dcs = $this->create_diet_check($id_p);
		$result = array();
		foreach($dcs as $dc){
			$query = $this->db->get_where('food_element', array('id' => $dc['id_food_element']));
			$food_el = $query->row_array();
			
			$id_time = $food_el['id_time'];
			$id_food = $food_el['id_food'];
			$amount = $food_el['amount'];
			
			
			$this->db->select('*');
			$this->db->from('food');
			$this->db->join('measure', 'measure.m_id = food.id_measure');
			$this->db->where(array('id' => $id_food));
			$query = $this->db->get('');
			$food = $query->row_array();
			$food_name = $food['name'];
			
			if(floatval($amount) < 2 )$food_measure = $food['m_name'];
			else $food_measure = $food['m_name_p'];
			
			if(floatval($food['m_name_p'])==1) $food_measure = ''; //Se for 'não tem'
			
			$amount_text = "";
			if($food['id_measure'] != 1){
				$amount_text = $amount.' '.$food_measure;
			}else{
				$amount_text = $amount * $food['gml'];
				$amount_text .= " (g/ml)";
			}
			$result[$id_time][] = array('id'=> $dc['id'],'food_measure' =>$food_measure, 'amount'=> $amount, 'food_name'=> $food_name, 'checked'=> $dc['checked'],'amount_text' => $amount_text);
		}
		return $result;
	}
	
	public function check_food(){
		$this->db->update('diet_check', array('checked' => 1), array('id' => $this->input->post('id_dc'))); 
	}
			
	public function uncheck_food(){
		$this->db->update('diet_check', array('checked' => 0), array('id' => $this->input->post('id_dc'))); 
	}
	
	//Cria acrescenta ao diet_check da pessoa, o elemneto de food_el
	public function new_diet_check($food_el,$id_diet){
		
		$data = array(
			'id_food_element' => $food_el ,
			'checked'		=> true ,
			'date'	=> date('Y-m-d'),
			'id_diet'		=> $id_diet
		);
		$this->db->insert('diet_check', $data);
		return $this->db->insert_id();
		
	}
	
	
		
}


?>
